
const rawbody = require('raw-body');
const contentType = require('content-type')
const convert = require('xml-js')


module.exports = async (ctx) => {
  let xml = await rawbody(ctx.req, {
    length: ctx.req.headers['content-length'],
    limit: '1mb',
    encoding: contentType.parse(ctx.req).parameters.charset
  })

  let result = convert.xml2js(xml, {
    compact: true,
    textKey: 'value',
    cdataKey: 'value'
  }).xml;

  //扁平化
  let obj = Object.keys(result).reduce((obj, key) => {
    obj[key] = result[key]['value']
    return obj;
  }, {})

  console.log('123', obj)
//   ctx.body = `
//   <xml>
//   <ToUserName><![CDATA[${obj.FromUserName}]]></ToUserName>
//   <FromUserName><![CDATA[${obj.ToUserName}]]></FromUserName>
//   <CreateTime>${new Date().toLocaleString()}</CreateTime>
//   <MsgType><![CDATA[text]]></MsgType>
//   <Content><![CDATA[<a href='https://www.web678.xyz/index.html'>gp18</a>]]></Content>
// </xml>
  
  // `
  await ctx.render('replay',{
    ...obj,
    createTime:new Date().toLocaleString(),
    content:"<a href='https://www.web678.xyz/index.html'>gp18</a>"
  })

}